﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HomeWork11_Order
{
    public class Order : IComparable
    {
        public int OrderId { get; set; }
        public string ClientName { get; set; }
        public double TotalMoney { get; set; }
        public int ClientId { get; set; }
        public Client Client { get; set; }
        public List<OrderItem> OrderItems { get; set; }
        public Order(int OrderID, Client Client)
        {
            OrderItems = new List<OrderItem>();
            this.OrderId = OrderID;
            this.Client = Client;
            TotalMoney = 0;
        }
        public Order() { }
        public bool AddOrderItem(OrderItem orderItemNew)
        {
            bool repeated = false;
            foreach (OrderItem orderItem in OrderItems)
            {
                if (orderItem.Equals(orderItemNew))
                    repeated = true;
            }
            if (!repeated)
            {
                this.OrderItems.Add(orderItemNew);
                this.TotalMoney += orderItemNew.ProductNumber * orderItemNew.Product.ProductPrice;
                using(var context=new OrderContext())
                {
                    context.OrderItems.Add(orderItemNew);
                }
                Console.WriteLine("添加订单明细成功！");
            }
            else { Console.WriteLine("已有重复订单明细！"); }
            return !repeated;
        }
        public int CompareTo(Object obj)
        {
            Order order = obj as Order;
            if (order == null)
                throw new System.ArgumentException();
            return this.OrderId.CompareTo(order.OrderId);
        }

        public override bool Equals(object obj)
        {
            return obj is Order order &&
                   OrderId == order.OrderId;
        }
        public override int GetHashCode()
        {
            var hashCode = 997595479;
            hashCode = hashCode * -1521134295 + OrderId.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Client.ClientName);
            return hashCode;
        }
        public override string ToString()
        {
            string str = $"OrderID: {OrderId} Client: {ClientName} TotalMoney:{TotalMoney}\r\n";
            using(var context =new OrderContext())
            {
                context.OrderItems.Where(o => o.OrderId == this.OrderId)
                    .ForEachAsync(o => Console.WriteLine(o));
            }
            return str;
        }
      
    }

}
